package com.wosai.teach.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wosai.teach.R;
import com.wosai.teach.adapter.HomeWorkAdapter;
import com.wosai.teach.cst.C;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.HomeWork;
import com.wosai.teach.entity.User;
import com.wosai.teach.utils.OtherUtils;

@ContentView(R.layout.activity_homework)
public class HomeWorkActivity extends AppActivity {

	private int pageSize = 10;

	private int curPage = 1;

	private User user;

	private HomeWorkAdapter adapter;

	@ViewInject(R.id.hw_list)
	private PullToRefreshListView hwList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmPageName("我的作业");
		setTopTitle("我的作业");
		enableBack(true);
		initView();
		loadInfo();
	}

	private void initView() {
		hwList.setMode(Mode.BOTH);
		List<HomeWork> workList = new ArrayList<HomeWork>();
		adapter = new HomeWorkAdapter(this, workList);
		hwList.setAdapter(adapter);
		hwList.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					final PullToRefreshBase<ListView> refreshView) {
				System.out.println("下拉刷新" + refreshView.getClass());
				curPage = 1;
				loadInfo();
			}

			@Override
			public void onPullUpToRefresh(
					final PullToRefreshBase<ListView> refreshView) {
				System.out.println("上拉加载" + refreshView.getClass());
				curPage++;
				loadInfo();
			}
		});
	}

	private void loadInfo() {
		user = db.findFirst(User.class);
		if (user == null) {
			Toast.makeText(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT)
					.show();
			Intent it = new Intent(this, LoginActivity.class);
			startActivity(it);
			finish();
		} else {

			String url = C.HTTP_URL_HOME_LIST;
			url = url.replace("{userId}", user.getUserId() + "");
			url = url.replace("{pageSize}", 5 + "");
			url = url.replace("{currentPage}", 1 + "");
			System.out.println(url);

			HttpUtils http = new HttpUtils();
			http.send(HttpRequest.HttpMethod.GET, url,
					new RequestCallBack<String>() {

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							if (OtherUtils.CheckNull(responseInfo.result)) {
								return;
							}
							JsonResult jr = JSON.parseObject(
									responseInfo.result, JsonResult.class);
							if (jr.getResult() == 0) {
								System.out.println("当前页||" + curPage);
								if (curPage == 1) {
									// 删除数据库
									db.deleteAll(Selector.from(HomeWork.class)
											.where("userId", "=",
													user.getUserId()));
								}
								List<HomeWork> expList = JSON
										.parseArray(jr.getObject().toString(),
												HomeWork.class);
								db.saveAll(expList);
								refreshRecList(expList);
							} else {
								if (curPage == 1) {
									List<HomeWork> expList = db
											.findAll(Selector
													.from(HomeWork.class));
									refreshRecList(expList);
								}
							}
							hwList.onRefreshComplete();
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							if (curPage == 1) {
								List<HomeWork> expList = db.findAll(Selector
										.from(HomeWork.class));
								refreshRecList(expList);
							}
							hwList.onRefreshComplete();
						}
					});

		}

	}

	private void refreshRecList(List<HomeWork> expList) {
		if (curPage == 1) {
			adapter.setList(expList);
		} else {
			adapter.addList(expList);
		}
		adapter.notifyDataSetChanged();
	}
}
